<?php

namespace App\Repositories\Api;

use App\Models\AccountRecord;
use App\Models\Member;
use App\Models\Picture;
use App\Models\PictureMapping;
use App\Models\Star;
use App\Models\TalkCategory;
use App\Models\Trend;
use App\Models\TrendComment;
use App\Repositories\PictureMappingRepository;
use App\Repositories\Api\MemberRepository;

class TrendRepository
{

    /**
     * 新增
     * @param $params
     */
    public function addTrend($params)
    {
        if (empty($params['content']) && empty($params['picture_ids'])) {
            return retFail("内容/图片至少填写一项");
        }

        if (!intval($params['talk_cid']))
            return retFail("话题必填");

        $data['content'] = trim($params['content']);
        $data['uid'] = $params['wechat_admin_id'];
        $data['talk_cid'] = intval($params['talk_cid']) ?? 0;
        $res = Trend::create($data);

        if (empty($res)) {
            return retFail("发布失败");
        }

        if (empty($params['picture_ids'])) {
            return retSuc([], "发布成功");
        }

        (new PictureMappingRepository())->updateMapping($res['id'], "trend", $params['picture_ids']);
        return retSuc(['id' => $res['id']], "发布成功");
    }

//    获取话题类型
    public function getTalkTypeList($params)
    {
        return TalkCategory::where(['status' => 1])
            ->orderBy("sort", "desc")
            ->orderBy("id", "desc")
            ->get(['id', 'title'])
            ->toArray();
    }

    /**
     * @param array $filter
     * @param int $pageSize
     * @param int $pageNum
     */
    public function getLists($filter = [], $pageSize = 10, $pageNum = 1)
    {
        $res = Trend::from("trend")
            ->join("talk_category as tc", "tc.id", "=", "trend.talk_cid")
            ->join("member as m", "m.id", "=", "trend.uid")
            ->when(!empty($filter['status']), function ($q) use ($filter) {
                if (is_array($filter['status'])) {
                    return $q->whereIn("trend.status", $filter['status']);
                } else {
                    return $q->where("trend.status", "=", $filter['status']);
                }
            })
            ->orderBy('trend.id', 'desc')
            ->paginate($pageSize, ['trend.*', 'tc.title as talk_title', 'm.username', 'm.gender', 'm.avatar', 'm.birthday', 'm.occuption'], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            $v['pictures'] = (new PictureMappingRepository())->getMappingBySearchFiter(['object_type' => "trend", 'object_id' => $v['id']]);
            $v['like_amount'] = Star::query()->where(['object_type' => "trend", 'object_id' => $v['id']])->count("id");
            $v['comment_amount'] = TrendComment::where(['object_id' => $v['id'], 'object_type' => "trend"])->count("id");
            $v['is_like'] = Star::query()->where(['object_type' => "trend", 'object_id' => $v['id'], 'uid' => UID])->count("id");
        }

        return $res;
    }

    public function like($object_id = null, $object_type = null, $uid = null)
    {
        if (empty($object_id) || !intval($uid))
            return retFail("参数错误");

        $star_id = Star::where(["object_id" => $object_id, 'object_type' => $object_type, "uid" => $uid])->value("id");
        if ($object_type == 'trend') {
            $trend_uid = Trend::where(['id' => $object_id])->value("uid");
        }

        if ($star_id) {
            Star::where("id", $star_id)->delete();

            if ($object_type == 'trend') {
                Trend::where("id", $object_id)->decrement("like_amount");
            } else {
                TrendComment::where("id", $object_id)->decrement("like_amount");
            }

            return retSuc(['status' => 2]);
        } else {
            Star::create([
                "object_id" => $object_id,
                'object_type' => $object_type,
                "uid" => $uid
            ]);

            if ($object_type == 'trend') {//动态点赞
                //大于等于100 奖励积分 5
                $like_amount = Star::where(["object_id" => $object_id, 'object_type' => $object_type])->count("id");
                if ($like_amount == 100 && !AccountRecord::where(['uid' => $trend_uid, 'object_id' => $object_id, 'object_type' => $object_type])->count("id")) {
                    (new MemberRepository())->change_user_account($trend_uid, null, null, 60, 5);
                }
                Trend::where("id", $object_id)->increment("like_amount");
            } else {
                TrendComment::where("id", $object_id)->increment("like_amount");
            }
            return retSuc(['status' => 1]);
        }
    }

    public function getOne($id = null)
    {
        if (empty(intval($id)))
            return null;

        $res = Trend::where(['id' => $id])->first();
        if (!empty($res)) {
            $res['member'] = Member::where(['id' => $res['uid']])->first(['id', 'avatar', 'username', 'birthday', 'location_city']);
            $res['pictures'] = (new PictureMappingRepository())->getMappingBySearch(['object_type' => "trend", 'object_id' => $res['id']]);
            $res['is_like'] = Star::query()->where(['object_id' => $res['id'], 'object_type' => "trend", 'uid' => UID])->count("id");
            $res['comment_amount'] = TrendComment::query()->where(['object_id' => $res['id'], 'object_type' => "trend"])->count("id");
            $res['talk_title'] = TalkCategory::where(['id' => $res['talk_cid']])->value("title");
        }

        return $res;
    }

//    获取最新的一条
    public function getLastest()
    {
        $res = Trend::where(['status' => 1])->orderBy("id", "desc")->first();
        if (!empty($res)) {
            $res['member'] = Member::where(['id' => $res['uid']])->first(['id', 'avatar', 'username', 'birthday', 'location_city']);
            $res['pictures'] = (new PictureMappingRepository())->getMappingBySearch(['object_type' => "trend", 'object_id' => $res['id']]);
            $res['is_like'] = Star::query()->where(['object_id' => $res['id'], 'object_type' => "trend", 'uid' => UID])->count("id");
            $res['comment_amount'] = TrendComment::query()->where(['object_id' => $res['id'], 'object_type' => "trend"])->count("id");
            $res['talk_title'] = TalkCategory::where(['id' => $res['talk_cid']])->value("title");
        }
        return $res;
    }
}
